const express = require("express")
const router = express.Router()
const {Comment} = require("../models")
const {Op} = require("sequelize")

const {NotFound, Forbidden} = require("http-errors")

const {success} = require("../utils/response")

/**
 * 发表评论
 */
router.post("/", async (req, res, next) => {
    try {
        const {content, userId, postId, parentId = null} = req.body

        let rootId = null
        let level = 1

        if(parentId) {
            const parentComment = await Comment.findByPk(parentId)
            if(!parentComment) throw new NotFound("父评论不存在")
            level = parentComment.level === 1 ? 2 : 3
            rootId = parentComment.rootId || parentComment.id
        }

        const comment = await Comment.create({
            content,
            userId,
            postId,
            parentId,
            rootId,
            level
        })

        success(res, "发表评论成功", comment)
    } catch(err) {
        next(err)
    }
})

/**
 * 删除评论
 */
router.delete("/:id", async (req, res, next) => {
    try {

        const comment = await Comment.findByPk(req.params.id)
        if(!comment) {
            throw new NotFound("评论不存在")
        }

        if(comment.userId !== req.body.userId) {
            throw new Forbidden("无权限删除此评论")
        }

        await comment.destroy()

        success(res, "删除评论成功")

    } catch(error) {
        console.log(error)
        next(error)
    }
})

module.exports = router